package com.bfly.mall.wechat.service.impl;

import com.bfly.core.base.service.BaseServiceImpl;
import com.bfly.core.enums.SysError;
import com.bfly.core.exception.ServiceResponseException;
import com.bfly.mall.wechat.dao.WeChatMpMapper;
import com.bfly.mall.wechat.dto.WeChatMpFormDTO;
import com.bfly.mall.wechat.entity.WeChatMp;
import com.bfly.mall.wechat.service.IWeChatMpService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;

/**
 * @author 长沙商脉科技有限公司
 * @date 2021/1/4 14:31
 */
@Service
@Transactional(propagation = Propagation.SUPPORTS)
public class WeChatMpServiceImpl extends BaseServiceImpl<WeChatMp, Integer> implements IWeChatMpService {

    @Autowired
    private WeChatMpMapper weChatMpMapper;

    @Override
    public WeChatMp getWeChatMp(String appId) {
        return weChatMpMapper.getWeChatMp(appId);
    }

    @Override
    public WeChatMp getWeChatMpByOriginId(String originId) {
        return weChatMpMapper.getWeChatMpByOriginId(originId);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void save(WeChatMpFormDTO formDTO) {
        WeChatMp mp = getWeChatMp(formDTO.getAppId());
        if (mp != null) {
            throw new ServiceResponseException(SysError.DATA_REPEAT, "AppId已重复!");
        }
        mp = getWeChatMpByOriginId(formDTO.getOriginId());
        if (mp != null) {
            throw new ServiceResponseException(SysError.DATA_REPEAT, "原始ID已重复!");
        }
        mp = new WeChatMp();
        BeanUtils.copyProperties(formDTO, mp);
        mp.setCreateDate(new Date());
        super.save(mp);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void edit(WeChatMpFormDTO formDTO) {
        WeChatMp mp = getWeChatMp(formDTO.getAppId());
        if (mp == null) {
            throw new ServiceResponseException(SysError.PARAM_ERROR, "不存在的公众号信息!");
        }
        if(!mp.getOriginId().equals(formDTO.getOriginId())){
            // 当原始ID不一样的时候 需要去验证是否重复
            mp = getWeChatMpByOriginId(formDTO.getOriginId());
            if (mp != null) {
                throw new ServiceResponseException(SysError.DATA_REPEAT, "原始ID已重复!");
            }
        }
        mp.setRemark(formDTO.getRemark());
        mp.setType(formDTO.getType());
        mp.setVerified(formDTO.isVerified());
        mp.setName(formDTO.getName());
        mp.setAppSecret(formDTO.getAppSecret());
        mp.setOwner(formDTO.getOwner());
        mp.setUpdateDate(new Date());
        mp.setQrCode(formDTO.getQrCode());
        super.edit(mp);
    }
}
